<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2022/4/20
 * Time: 4:44 PM
 */

namespace app\api\command;


use app\api\extend\tools\SimpleModelConnectRedis;
use app\api\service\UserFollowService;
use app\api\service\UserService;
use app\api\service\WeminiService;
use think\admin\Command;
use think\console\Input;
use think\console\Output;

/**
 * Class Friend
 * @package app\api\command
 */
class Friend extends Command
{
    protected $module = ['join_list', 'audit_list'];

    protected $sleep_time = 5 * 60;
    protected $miniprogram_state = 'trial';//developer为开发版；trial为体验版；formal为正式版

    /**
     * 执行指令
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     */
    protected function execute(Input $input, Output $output)
    {
        foreach ($this->module as $m) {
            if (method_exists($this, $fun = "_{$m}")) $this->$fun();
        }
    }

    /**
     * 加好友
     */
    protected function _join_list()
    {
        $pri = 'join_friend.';
        $this->output->comment($pri . 'execute.start:' . date('Y-m-d H:i:s', time()));
        $limit = 100;
        $redis = SimpleModelConnectRedis::getInstance();
        $key = USER_FARIAEND_JOIN_LIST . '_*';
        $ndata = $redis->key_scan_list($key, $limit, $redis);
        if (empty($ndata)) {
            $this->output->info($pri . 'error：key_scan_list');
            sleep($this->sleep_time);
            exit;
        }
        $this->output->info($pri . 'scan.data:' . json_encode($ndata));
        foreach ($ndata as $val) {
            $redis_key = $val;
            $flag = $redis->exists($redis_key);
            if (!$flag) {
                $this->output->error($pri . 'error：not find redis key.');
                continue;
            }
            $len = $redis->lLen($redis_key);
            $len = $len > 20 ? 20 : $len;//10个一组
            $b = $len <= 0 ? 1 : $len;
            $data = [];
            for ($i = 0; $i < $b; $i++) {
                $resdata = json_decode($redis->rpop($redis_key), true);
                if (!empty($resdata)) {
                    $data[] = [
                        'user_id' => isset($resdata['user_id']) ? (int)$resdata['user_id'] : 0,
                        'focus_user_id' => isset($resdata['focus_user_id']) ? (int)$resdata['focus_user_id'] : 0,
                        'join_time' => isset($resdata['join_time']) ? $resdata['join_time'] : '',
                    ];
                }

            }
        }
        if (!empty($data)) {
            $this->output->info($pri . 'data:' . json_encode($data));
            foreach ($data as $value) {
                try {
                    $user_id = isset($value['user_id']) ? (int)$value['user_id'] : 0;
                    $focus_user_id = isset($value['focus_user_id']) ? (int)$value['focus_user_id'] : 0;
                    $date1 = isset($value['join_time']) ? $value['join_time'] : date('Y-m-d H:i:s', time());
                    $focus_user = UserService::get($focus_user_id, 'id,openid');
                    $user = UserService::get($user_id, 'id,uname');
                    $tmplid_arr = TMPLIDS_ARR;
                    $template_id = isset($tmplid_arr[0]['value']) ? $tmplid_arr[0]['value'] : '';
                    $page = isset($tmplid_arr[0]['path']) ? $tmplid_arr[0]['path'] : '';
                    if (!empty($user['uname']) && !empty($focus_user['openid']) && !empty($template_id)) {
                        /*******************************发送订阅消息********************************/
                        $send_data = [
                            'touser' => $focus_user['openid'],
                            'template_id' => $template_id,
                            'miniprogram_state' => $this->miniprogram_state,
                            'page' => $page,
                        ];
                        $ndata = [
                            'date1' => [
                                'value' => $date1
                            ],
                            'name2' => [
                                'value' => $user['uname']//urlencode
                            ],
                            'thing3' => [
                                'value' => '您好,我是' . $user['uname'] . '，麻烦通过一下'
                            ],
                        ];
                        $send_data['data'] = $ndata;
                        $result_data = WeminiService::sendMsg($send_data);
                        $this->output->info($pri . 'sendMsg.result：' . json_encode(['send_data' => $send_data, 'result_data' => $result_data]));
                    }
                } catch (\Exception $exception) {
                    $this->output->error($pri . 'execute.exception:' . $exception->getMessage());
                    $key = USER_FARIAEND_JOIN_LIST . '_' . date('Ymd', time());
                    $redis->lPush($key, json_encode($value));
                }

            }
        }
        $this->output->comment($pri . 'execute.end_' . date('Y-m-d H:i:s', time()));
        $this->output->newLine();
    }


    /**
     * 审核
     */
    protected function _audit_list()
    {
        $pri = 'audit_friend.';
        $this->output->comment($pri . 'execute.start:' . date('Y-m-d H:i:s', time()));
        $limit = 100;
        $redis = SimpleModelConnectRedis::getInstance();
        $key = USER_FARIAEND_AUDIT_LIST . '_*';
        $ndata = $redis->key_scan_list($key, $limit, $redis);
        if (empty($ndata)) {
            $this->output->info($pri . 'error：key_scan_list');
            sleep($this->sleep_time);
            exit;
        }
        $this->output->info($pri . 'scan.data:' . json_encode($ndata));
        foreach ($ndata as $val) {
            $redis_key = $val;
            $flag = $redis->exists($redis_key);
            if (!$flag) {
                $this->output->error($pri . 'error：not find redis key.');
                continue;
            }
            $len = $redis->lLen($redis_key);
            $len = $len > 20 ? 20 : $len;//10个一组
            $b = $len <= 0 ? 1 : $len;
            $data = [];
            for ($i = 0; $i < $b; $i++) {
                $resdata = json_decode($redis->rpop($redis_key), true);
                if (!empty($resdata)) {
                    $data[] = [
                        'user_id' => isset($resdata['user_id']) ? (int)$resdata['user_id'] : 0,
                        'id' => isset($resdata['id']) ? (int)$resdata['id'] : 0,
                        'audit_time' => isset($resdata['audit_time']) ? $resdata['audit_time'] : '',
                    ];
                }

            }
        }
        if (!empty($data)) {
            $this->output->info($pri . 'data:' . json_encode($data));
            foreach ($data as $value) {
                try {
                    $status = isset($value['status']) ? (int)$value['status'] : 0;
                    $id = isset($value['id']) ? (int)$value['id'] : 0;
                    $date1 = isset($value['audit_time']) ? $value['audit_time'] : date('Y-m-d H:i:s', time());
                    $follow_data = UserFollowService::get(['id' => $id]);
                    $user_id = !empty($follow_data) ? $follow_data['user_id'] : 0;
                    $user = UserService::get($user_id, 'id,uname,openid');
                    $tmplid_arr = TMPLIDS_ARR;
                    $template_id = isset($tmplid_arr[1]['value']) ? $tmplid_arr[1]['value'] : '';
                    $page = isset($tmplid_arr[1]['path']) ? $tmplid_arr[1]['path'] : '';
                    if (!empty($follow_data) && !empty($user['openid']) && !empty($template_id)) {
                        /*******************************发送订阅消息********************************/
                        $send_data = [
                            'touser' => $user['openid'],
                            'template_id' => $template_id,
                            'miniprogram_state' => $this->miniprogram_state,//developer为开发版；trial为体验版；formal为正式版
                            'page' => $page,
                        ];
                        $ndata = [
                            'thing30' => [
                                'value' => $status == 1 ? '您的好友同意了您的好友申请' : '您提交的好友申请已被拒绝'
                            ],
                            'phrase1' => [
                                'value' => $status == 1 ? '通过' : '不通过'
                            ],
                            'thing7' => [
                                'value' => '如有疑问请联系客服'
                            ],
                        ];
                        $send_data['data'] = $ndata;
                        $result_data = WeminiService::sendMsg($send_data);
                        $this->output->info($pri . 'sendMsg.result：' . json_encode(['send_data' => $send_data, 'result_data' => $result_data]));
                    }
                } catch (\Exception $exception) {
                    $this->output->error($pri . 'execute.exception:' . $exception->getMessage());
                    $key = USER_FARIAEND_AUDIT_LIST . '_' . date('Ymd', time());
                    $redis->lPush($key, json_encode($value));
                }

            }
        }
        $this->output->comment($pri . 'execute.end_' . date('Y-m-d H:i:s', time()));
        $this->output->newLine();
    }
}